import React from 'react'
import PropTypes from 'prop-types'
import { sexTypeData, LicenseType } from 'utils/seletLocalData'
import moment from 'moment'
import { config, converDate, defaultValue, SelectProps, productMention, findValueByKey } from 'utils'
import { titleType } from 'enums'
import { Form, Input, InputNumber, Row, Col, Button, Icon, DatePicker, Select, Tooltip, Table } from 'antd'
import { isConstructorTypeNode } from 'typescript'
import { connect } from 'dva'
import { routerRedux } from 'dva/router'
import styles from '../../../themes/detail.less'
import { UploadPhotos } from '../../../components/Upload_photos/index.js'
import TableCard from '../../../components/TableCard'

const { TextArea } = Input
const FormItem = Form.Item
const ButtonGroup = Button.Group
const Option = Select.Option
const formItemLayout = {
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 16,
  },
}
const ButtonProps = {
  size: 'large',
  style: {
    marginBottom: 0,
  },
}
const CustomerDetail = ({
  customerDetail,
  dispatch,
  loading,
  form: {
    getFieldDecorator,
    validateFields,
    getFieldsValue,
  },
}) => {
  const personInfo = customerDetail.data.person || {}
  const dateFormat = 'DD/MM/YYYY'
  const customerInfo = customerDetail.data
  const { editType, countryCodeData, licenseType1, licenseType2, fileList, identifierTypeData, identifyTypeList } = customerDetail
  const handleOk = () => {
    validateFields((errors) => {
      if (errors) {
        return
      }
      let fieldsValues = getFieldsValue()
      const data = {
        ...fieldsValues,
      }
      let dataFormatField = ['id1StartDate', 'id1DueDate', 'id2StartDate', 'id2DueDate', 'birthdate']
      dataFormatField.forEach((value) => {
        if (data[value]) {
          data[value] = data[value].format('YYYY-MM-DD')
        }
      })
      let customerSendData = {
        id: '',
        customerNumber: '1', // 先默认为一
        idNumber1: '',
        id1StartDate: '',
        id1DueDate: '',
        idNumber2: '',
        id2StartDate: '',
        id2DueDate: '',
        firstName: '',
        middleName: '',
        lastName: '',
        averageAnnualTurnover: 0,
        phoneNumber: '',
        IRDNumber: '',
        tradingFrequency: 0,
        licenseType1: '',
        licenseType2: '',
        fundUse: '',
      }
      for (let o in customerSendData) {
        customerSendData[o] = data[o]
      }
      let personSendData = {
        id: '',
        alias: '',
        gender: '',
        firstName: '',
        middleName: '',
        lastName: '',
        nationality1: '',
        nationality2: '',
        nationality3: '',
        birthdate: '',
        birthPlace: '',
        email: '',
        taxNumber: '',
        taxRegNumber: '',
        title: '',
        comments: '',
        occupation: '',
        employerName: '',
        sourceOfWealth: '',
      }
      for (let o in personSendData) {
        personSendData[o] = data[o]
      }
      let identifySendData = {
        type: '',
        issueCountry: '',
        number: '',
      }
      for (let o in identifySendData) {
        identifySendData[o] = data[o]
      }
      customerSendData.person = personSendData
      if (editType === 'create') {
        customerSendData.id = 1
        customerSendData.person.id = 1
      } else {
        customerSendData.id = customerInfo.id
        customerSendData.person.id = personInfo.id
      }
      customerSendData.identifications = [identifySendData]
      if (editType === 'create') {
        customerSendData.id = 1
        customerSendData.person.id = 1
      } else {
        customerSendData.id = customerInfo.id
        customerSendData.person.id = personInfo.id
      }
      dispatch({
        type: `customerDetail/${editType}`,
        payload: customerSendData,
      })
    })
  }
  const mention = productMention('AverageAnnualTurnover')
  const onSearch = () => {
    dispatch(routerRedux.push({
      pathname: '/customer',
    }))
  }

  const onSave = () => {
    handleOk()
  }
  const onAddress = () => {
    dispatch(routerRedux.push({
      pathname: `/address/${personInfo.id}/customerAddress`,
    }))
  }

  const onAccout = () => {
    dispatch(routerRedux.push({
      pathname: `/accout/${customerInfo.id}`,
    }))
  }

  const onIdentification = () => {
    dispatch(routerRedux.push({
      pathname: `/ident/${personInfo.id}/customerIdent`,
    }))
  }

  const onPhone = () => {
    dispatch(routerRedux.push({
      pathname: `/phone/${personInfo.id}/customerPhone`,
    }))
  }

  const onEmployerAddress = () => {
    dispatch(routerRedux.push({
      pathname: `/employeraddress/${personInfo.id}/customerEmployer`,
    }))
  }

  const onEmployerPhone = () => {
    dispatch(routerRedux.push({
      pathname: `/employerphone/${personInfo.id}/customerEmployer`,
    }))
  }


  const onEntity = () => {
    dispatch(routerRedux.push({
      pathname: `/entity/${customerInfo.id}`,
    }))
  }
  const onDelete = () => {

  }
  const handleLicenseTypeChange1 = (value) => {
    dispatch({
      type: 'customerDetail/updateCustomer',
      payload: {
        licenseType1: value,
      },
    })
  }

  const handleLicenseTypeChange2 = (value) => {
    dispatch({
      type: 'customerDetail/updateCustomer',
      payload: {
        licenseType2: value,
      },
    })
  }
  const nationality1Props = {
    personInfo,
    customerInfo,
    type: customerInfo.licenseType1,
  }
  const nationality2Props = {
    personInfo,
    customerInfo,
    type: customerInfo.licenseType2,
  }
  let objectItem = {
    type: 'ccsac',
    personInfo: {},
    customerInfo: {},
  }
  const uploadPhotoProps = {
    fileList,
    handleUpload (file) {
      let param = new FormData()
      param.append('file', file, file.name)
      dispatch({
        type: 'customerDetail/uploadfile',
        payload: param,
      })
    },
    handleRemove (file) {
      console.log(file, 'cnsaincsa')
      let result = fileList.filter(value => value.id !== file.id)
      dispatch({
        type: 'customerDetail/updateState',
        payload: {
          fileList: result,
        },
      })
    },
  }
  const sexData = sexTypeData.map(d => <Option key={d.key}>{d.value}</Option>)
  const countryCode = countryCodeData.map(d => <Option key={d.code}>{d.name}</Option>)
  const LicenseTypeOptions = LicenseType.map(d => <Option key={d.key}>{d.value}</Option>)
  const titleData = titleType.map(d => <Option key={d.key}>{d.value}</Option>)
  let blocks = []
  identifyTypeList.forEach((current) => {
    const block = [{
      title: 'Type',
      key: findValueByKey(identifierTypeData, current.type, 'code'),
    }, {
      title: 'Number',
      key: current.number,
    }, {
      title: 'IssueCountry',
      key: findValueByKey(countryCodeData, current.issueCountry, 'code'),
    }]
    blocks.push(...block)
  })
  // const tableProps = {
  //   blocks,
  //   cols: 3,
  //   rows: 5,
  //   type: 'table',
  // }
  const tableProps = {
    dataSource: identifyTypeList,
    columns: [
      {
        title: 'Type',
        dataIndex: 'type',
        key: 'type',
        render: (record) => {
          const data = findValueByKey(identifierTypeData, record, 'code')
          return data
        },
      },
      {
        title: 'Number',
        dataIndex: 'number',
        key: 'number',
      },
      {
        title: 'IssueCountry',
        dataIndex: 'issueCountry',
        key: 'issueCountry',
        render: (record) => {
          const data = findValueByKey(countryCodeData, record, 'code')
          return data
        },
      },
    ],
    pagination: false,
  }
  const listenceTypeCreate = (licenseType) => {
    return (
      <Row gutter={0}>
        <Col span={8}>
          <FormItem label="passportNO" hasFeedback {...formItemLayout}>
            {getFieldDecorator(`idNumber${licenseType}`, {
              initialValue: customerInfo[`idNumber${licenseType}`],
            })(<Input />)}
          </FormItem>
        </Col>
        <Col span={8}>
          <FormItem label="Issue date" hasFeedback {...formItemLayout}>
            {getFieldDecorator(`id${licenseType}StartDate`, {
              initialValue: customerInfo[`id${licenseType}StartDate`] ? moment(converDate(customerInfo[`id${licenseType}StartDate`]), dateFormat) : '',
            })(<DatePicker style={{ width: '100%' }} format={dateFormat} />)}
          </FormItem>
        </Col>
        <Col span={8}>
          <FormItem label="Due date" hasFeedback {...formItemLayout}>
            {getFieldDecorator(`id${licenseType}DueDate`, {
              initialValue: customerInfo[`id${licenseType}DueDate`] ? moment(converDate(customerInfo[`id${licenseType}DueDate`]), dateFormat) : '',
            })(<DatePicker style={{ width: '100%' }} format={dateFormat} />)}
          </FormItem>
        </Col>
        {
          (licenseType === '1') && <Col span={8}>
            <FormItem label="passportCountry" hasFeedback {...formItemLayout}>
              {getFieldDecorator('passportCountry', {
                initialValue: personInfo.passportCountry,
              })(<Input />)}
            </FormItem>
          </Col>
        }
      </Row>
    )
  }
  return (
    <Form layout="horizontal">
      {editType === 'update' ? <div className={styles.div_buttonGroup}>
        <ButtonGroup {...ButtonProps}>
          <Button onClick={onPhone}>
            Phone<Icon type="phone" />
          </Button>
          <Button onClick={onAddress}>
            Address<Icon type="environment-o" />
          </Button>
          <Button onClick={onIdentification}>
            Identification<Icon type="idcard" />
          </Button>
          <Button onClick={onEmployerPhone}>
            EmployerPhone<Icon type="user" />
          </Button>
          <Button onClick={onEmployerAddress}>
            EmployerAddress<Icon type="user" />
          </Button>
          <Button onClick={onAccout}>
            Account<Icon type="bank" />
          </Button>
          <Button onClick={onEntity}>
            Entity<Icon type="team" />
          </Button>
        </ButtonGroup>
      </div> : <div />}
      <div className={styles.div_buttonGroup}>
        <ButtonGroup {...ButtonProps}>
          <Button onClick={handleOk} loading={loading.effects[`customerDetail/${editType}`]}>
            Save<Icon type="save" />
          </Button>
          <Button onClick={onSearch}>
            Search<Icon type="search" />
          </Button>
          { editType === 'update' &&
            <Button onClick={onDelete}>
              Delete<Icon type="delete" />
            </Button>
          }
        </ButtonGroup>
      </div>
      <div className={styles.div_form}>
        <div className={styles.title}>BasicInfo</div>
        <Row>
          <Col span={8}>
            <FormItem label="CustomerNO" hasFeedback {...formItemLayout}>
              {getFieldDecorator('customerNumber', {
                initialValue: customerInfo.customerNumber,
              })(<Input disabled />)}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="Title" hasFeedback {...formItemLayout}>
              {getFieldDecorator('title', {
                initialValue: personInfo.title,
              })(<Select style={{ width: '100%' }}{...SelectProps}>{titleData}</Select>)}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="Gender" hasFeedback {...formItemLayout}>
              {getFieldDecorator('gender', {
                initialValue: personInfo.gender,
                rules: [
                  {
                    required: true,
                  },
                ],
              })(<Select style={{ width: '100%' }}>{sexData}</Select>)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={0}>
          <Col span={8}>
            <FormItem label="LastName" hasFeedback {...formItemLayout}>
              {getFieldDecorator('lastName', {
                initialValue: personInfo.lastName,
                rules: [
                  {
                    required: true,
                    max: 255,
                  },
                ],
              })(<Input />)}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="MiddleName" hasFeedback {...formItemLayout}>
              {getFieldDecorator('middleName', {
                initialValue: personInfo.middleName,
                rules: [
                  {
                    max: 255,
                  },
                ],
              })(<Input />)}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="FirstName" hasFeedback {...formItemLayout}>
              {getFieldDecorator('firstName', {
                initialValue: personInfo.firstName,
                rules: [
                  {
                    required: true,
                    max: 255,
                  },
                ],
              })(<Input />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={0}>
          <Col span={8}>
            <FormItem label="Alias" hasFeedback {...formItemLayout}>
              {getFieldDecorator('alias', {
                initialValue: personInfo.alias,
                rules: [
                  {
                    max: 255,
                  },
                ],
              })(<Input />)}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="BirthPlace" hasFeedback {...formItemLayout}>
              {getFieldDecorator('birthPlace', {
                initialValue: personInfo.birthPlace,
                rules: [
                  {
                    required: true,
                  },
                ],
              })(<Input />)}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="Birthdate" hasFeedback {...formItemLayout}>
              {getFieldDecorator('birthdate', {
                initialValue: personInfo.birthdate && moment(converDate(personInfo.birthdate), dateFormat),
                rules: [
                  {
                    required: true,
                  },
                ],
              })(<DatePicker style={{ width: '100%' }} format={dateFormat} />)}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="Email" hasFeedback {...formItemLayout}>
              {getFieldDecorator('email', {
                initialValue: personInfo.email,
                rules: [
                  {
                    pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/,
                    message: 'E-mail pattern error!',
                  },
                ],
              })(<Input />)}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="Phone" hasFeedback {...formItemLayout}>
              {getFieldDecorator('phoneNumber', {
                initialValue: customerInfo.phoneNumber,
                rules: [
                  {
                    required: true,
                  },
                ],
              })(<Input />)}
            </FormItem>
          </Col>
        </Row>
        <div style={{ display: 'flex' }} >
          <div className={styles.title}>IdentityInfo</div>
          {
            editType === 'update' &&
            <Icon type="edit" style={{ marginLeft: '20px', cursor: 'pointer' }} onClick={onIdentification} >update</Icon>
          }
        </div>
        {editType === 'update' ? (
          <Row style={{ margin: '0 30px 15px 30px' }}>
            <Col>
              <Table {...tableProps} />
            </Col>
          </Row>) : (
          <Row gutter={0}>
            <Col span={8}>
              <FormItem label="LicenseType" hasFeedback {...formItemLayout}>
                {getFieldDecorator('type', {
                  initialValue: defaultValue(customerInfo.licenseType1, 'licenseType'),
                  rules: [
                    {
                      required: true,
                    },
                  ],
                })(<Select style={{ width: '100%' }} onChange={handleLicenseTypeChange1}>{LicenseTypeOptions}</Select>)}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem label="Number" hasFeedback {...formItemLayout}>
                {getFieldDecorator('number', {
                  initialValue: defaultValue(customerInfo.idNumber1, 'number'),
                  rules: [
                    {
                      required: true,
                    },
                  ],
                })(<Input />)}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem label="Country" hasFeedback {...formItemLayout}>
                {getFieldDecorator('issueCountry', {
                  initialValue: defaultValue(personInfo.nationality1, 'nationality'),
                  rules: [
                    {
                      required: true,
                    },
                  ],
                })(<Select style={{ width: '100%' }}{...SelectProps}>{countryCode}</Select>)}
              </FormItem>
            </Col>
          </Row>)
        }
        {/*<Row gutter={0}>*/}
          {/*<Col span={8}>*/}
            {/*<FormItem label="Nationality1" hasFeedback {...formItemLayout}>*/}
              {/*{getFieldDecorator('nationality1', {*/}
                {/*initialValue: defaultValue(personInfo.nationality1, 'nationality'),*/}
              {/*})(<Select style={{ width: '100%' }}{...SelectProps}>{countryCode}</Select>)}*/}
            {/*</FormItem>*/}
          {/*</Col>*/}
          {/*<Col span={8}>*/}
            {/*<FormItem label="LicenseType1" hasFeedback {...formItemLayout}>*/}
              {/*{getFieldDecorator('licenseType1', {*/}
                {/*initialValue: defaultValue(customerInfo.licenseType1, 'licenseType'),*/}
              {/*})(<Select style={{ width: '100%' }} onChange={handleLicenseTypeChange1}>{LicenseTypeOptions}</Select>)}*/}
            {/*</FormItem>*/}
          {/*</Col>*/}
        {/*</Row>*/}
        {/*{*/}
          {/*customerInfo.licenseType1 === '1' ? listenceTypeCreate('1') : ''*/}
        {/*}*/}
        {/*{*/}
          {/*customerInfo.licenseType1 === '2' ? listenceTypeCreate('2') : ''*/}
        {/*}*/}
        {/*{*/}
          {/*customerInfo.licenseType1 === '3' ? <div>*/}
            {/*{*/}
              {/*listenceTypeCreate('1')*/}
            {/*}*/}
            {/*{*/}
              {/*listenceTypeCreate('2')*/}
            {/*}*/}
          {/*</div> : ''*/}
        {/*}*/}
        {/*<Row>*/}
          {/*<Col span={8}>*/}
            {/*<FormItem label="Nationality2" hasFeedback {...formItemLayout}>*/}
              {/*{getFieldDecorator('nationality2', {*/}
              {/*})(<Select style={{ width: '100%' }} {...SelectProps}>{countryCode}</Select>)}*/}
            {/*</FormItem>*/}
          {/*</Col>*/}
          {/*<Col span={8}>*/}
            {/*<FormItem label="LicenseType2" hasFeedback {...formItemLayout}>*/}
              {/*{getFieldDecorator('licenseType2', {*/}
                {/*initialValue: defaultValue(customerInfo.licenseType2, 'licenseType'),*/}
              {/*})(<Select style={{ width: '100%' }} onChange={handleLicenseTypeChange2}>{LicenseTypeOptions}</Select>)}*/}
            {/*</FormItem>*/}
          {/*</Col>*/}
        {/*</Row>*/}
        {/*{*/}
          {/*customerInfo.licenseType2 === '1' ? listenceTypeCreate('1') : ''*/}
        {/*}*/}
        {/*{*/}
          {/*customerInfo.licenseType2 === '2' ? listenceTypeCreate('2') : ''*/}
        {/*}*/}
        {/*{*/}
          {/*customerInfo.licenseType2 === '3' ? <div>*/}
            {/*{*/}
              {/*listenceTypeCreate('1')*/}
            {/*}*/}
            {/*{*/}
              {/*listenceTypeCreate('2')*/}
            {/*}*/}
          {/*</div> : ''*/}
        {/*}*/}
        <div className={styles.title}>OtherInfo</div>
        <Row>
          <Col span={8}>
            <FormItem label="Occupation" hasFeedback {...formItemLayout}>
              {getFieldDecorator('occupation', {
                initialValue: personInfo.occupation,
              })(<Input />)}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="Employer Name" hasFeedback {...formItemLayout}>
              {getFieldDecorator('employerName', {
                initialValue: personInfo.employerName,
              })(<Input />)}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="IRD Number" hasFeedback {...formItemLayout}>
              {getFieldDecorator('IRDNumber', {
                initialValue: customerInfo.IRDNumber,
              })(<Input />)}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label="Source of Wealth" hasFeedback {...formItemLayout}>
              {getFieldDecorator('sourceOfWealth', {
                initialValue: personInfo.sourceOfWealth,
              })(<Input />)}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="Average.A.T" hasFeedback {...formItemLayout}>
              {getFieldDecorator('averageAnnualTurnover', {
                initialValue: customerInfo.averageAnnualTurnover,
              })(<Input />)}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="TradingFrequency" hasFeedback {...formItemLayout}>
              {getFieldDecorator('tradingFrequency', {
                initialValue: customerInfo.tradingFrequency,
              })(<Input />)}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label="UseOfFunds" hasFeedback {...formItemLayout}>
              {getFieldDecorator('fundUse', {
                initialValue: customerInfo.fundUse,
              })(<Input />)}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="comments" hasFeedback {...formItemLayout}>
              {getFieldDecorator('comments', {
                initialValue: personInfo.comments,
              })(<TextArea autosize={{ minRows: 4, maxRows: 6 }} />)}
            </FormItem>
          </Col>
          <Col span={8} offset={1}>
            <div style={{ display: 'flex', justifyContent: 'start' }}>
              <div style={{ padding: '0 10px 0 0' }}>Upload photos:</div>
              <UploadPhotos {...uploadPhotoProps} />
            </div>
          </Col>
        </Row>
      </div>
    </Form>

  )
}

CustomerDetail.propTypes = {
  form: PropTypes.object.isRequired,
  dispatch: PropTypes.func,
  loading: PropTypes.object,
  customerDetail: PropTypes.object,
}

export default connect(({ customerDetail, loading }) => ({ customerDetail, loading }))(Form.create()(CustomerDetail))
